﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.Admin.ArticleManage
{
	public partial class ArticleList : BasePage
	{
        protected override void OnPreRender(EventArgs e)
        {
            Hxsoft.AppV1.Page page = this.Page as Hxsoft.AppV1.Page;
            if (page != null)
            {
                page.RegisterHeadIncludeFile(ApplicationConfiguration.JQueryUrl, IncludeFileType.JS);
                page.RegisterHeadIncludeFile(ApplicationConfiguration.JQueryCluetipUrl, IncludeFileType.JS);
                page.RegisterHeadIncludeFile(ApplicationConfiguration.JQueryCluetipStyleUrl, IncludeFileType.CSS);

                ScriptManager.RegisterStartupScript(this, this.GetType(), "Init", "$(function(){ " + this.ClientID + "_Init(); });", true);
            }
            base.OnPreRender(e);
        }

		#region 事件
		protected void pager_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
		{
			pager.CurrentPageIndex = e.NewPageIndex;
			LoadList();
		}

		protected void BtSearch_Click(object sender, EventArgs e)
		{
			pager.CurrentPageIndex = 1;
			LoadList();
		}

		protected void BtReload_Click(object sender, EventArgs e)
		{
			LoadList();
		}

		protected void List_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			int identifier = GetListItemIdentifier(e.Item);
			string messages = "";

			switch (e.CommandName)
			{
				case "Delete":
					messages = Delete(identifier);
					break;
				case "SetEffectiveState":
					messages = SetEffectiveState(identifier);
					break;
				case "SetOpenComment":
					messages = SetOpenComment(identifier);
					break;
			}

			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messages));
			}

			LoadList();
		}

		protected void BtDelete_ServerClick(object sender, EventArgs e)
		{
			int identifier;
			string messages = "";

			foreach (RepeaterItem item in List.Items)
			{
				if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
				{
					CheckBox cbSelect = (CheckBox)item.FindControl("CbSelect");
					if (!cbSelect.Checked)
						continue;

					identifier = GetListItemIdentifier(item);
					string message = Delete(identifier);

					if (!String.IsNullOrEmpty(message))
						messages += "<li>[" + identifier.ToString() + "]" + message + "</li>";
				}
			}

			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messages));
			}

			LoadList();
		}

		// 设置有效状态  
		protected void BtSetEffectiveState_ServerClick(object sender, EventArgs e)
		{
			int identifier;
			string messages = "";

			foreach (RepeaterItem item in List.Items)
			{
				if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
				{
					CheckBox cbSelect = (CheckBox)item.FindControl("CbSelect");
					if (!cbSelect.Checked)
						continue;

					identifier = GetListItemIdentifier(item);
					string message = SetEffectiveState(identifier);

					if (!String.IsNullOrEmpty(message))
						messages += "<li>[" + identifier.ToString() + "]" + message + "</li>";
				}
			}

			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messages));
			}

			LoadList();
		}

		// 设置评论状态
		protected void BtSetOpenComment_ServerClick(object sender, EventArgs e)
		{
			int identifier;
			string messages = "";

			foreach (RepeaterItem item in List.Items)
			{
				if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
				{
					CheckBox cbSelect = (CheckBox)item.FindControl("CbSelect");
					if (!cbSelect.Checked)
						continue;

					identifier = GetListItemIdentifier(item);
					string message = SetOpenComment(identifier);

					if (!String.IsNullOrEmpty(message))
						messages += "<li>[" + identifier.ToString() + "]" + message + "</li>";
				}
			}

			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messages));
			}

			LoadList();
		}
		#endregion


		#region 函数方法

		/// <summary>
		/// 加载列表。
		/// </summary>
		protected void LoadList()
		{
			PaginationInfo<List<Articles.ArticleForManageList>> pageInfo =
				Articles.GetPaginationManageList(IntExtensions.ParseOrNull(TbID.Text)
					, BooleanExtensions.ParseOrNull(DdlIsEffective.SelectedValue)
					, TbUserName.Text
					, DateTimeExtensions.ParseOrNull(JtbStartRegisterDate.Text)
					, DateTimeExtensions.ParseOrNull(JtbEndRegisterDate.Text)
					, TbKeyword.Text
					, pager.PageSize, pager.CurrentPageIndex);

			pager.RecordCount = pageInfo.RecordCount;

			List.DataSource = pageInfo.Records;
			List.DataBind();

			pager.CustomInfoHTML = Helper.GetPagerCustomInfoHtml<List<Articles.ArticleForManageList>>(pageInfo);
		}


        protected string ItemCreateName
        {
            get {
                var userName = Eval("CreatorName","");
                if (string.IsNullOrEmpty(userName)) return userName;

                var userId=Users.GetUserId(userName);

                if(!userId.HasValue) return userName;

                if (CompanyUsers.Exists(userId.Value))
                    return CompanyUsers.GetUser(userName).RealName;

                return userName;
            }
        }

		/// <summary>
		/// 取得 ListItem 的标识符。
		/// </summary>
		/// <param name="item">列表的 ListItem。</param>
		/// <returns>ListItem 的标识符。</returns>
		protected int GetListItemIdentifier(RepeaterItem item)
		{
			int identifier;
			HiddenField control;

			control = (HiddenField)item.FindControl("Identifier_ArticleID");
			identifier = Convert.ToInt32(control.Value);

			return identifier;
		}

		/// <summary>
		/// 删除指定的信息
		/// </summary>
		/// <param name="identifier">要删除信息的标识符。</param>
		/// <returns>如果删除发生错误则返回错误消息。</returns>
		protected string Delete(int identifier)
		{
			if (Articles.GetDeleteRight(Articles.GetItem(identifier)))
			{
				Articles.Delete(identifier);
				return null;
			}
			else
				return string.Format(Res.PermissionException_DeleteAppointedObject, identifier);
		}

		/// <summary>
		/// 设置指定的信息的有效状态。
		/// </summary>
		/// <param name="identifier">要设置信息的标识符。</param>
		/// <returns>如果设置发生错误则返回错误消息。</returns>
		protected string SetEffectiveState(int identifier)
		{
			if (Articles.GetSetEffectiveStateRight(Articles.GetItem(identifier)))
			{
				Articles.SetEffectiveState(identifier);
				return null;
			}
			else
				return string.Format(Res.PermissionException_SettingAppointedObject, identifier);
		}

		/// <summary>
		/// 设置指定的信息的评论状态。
		/// </summary>
		/// <param name="identifier">要设置信息的标识符。</param>
		/// <returns>如果设置发生错误则返回错误消息。</returns>
		protected string SetOpenComment(int identifier)
		{
			if (Articles.GetSettingRight(Articles.GetItem(identifier)))
			{
				SetCommentState(identifier);
				//Article.SetOpenComment(identifier);
				return null;
			}
			else
				return string.Format(Res.PermissionException_SettingAppointedObject, identifier);
		}

		/// <summary>
		/// 获取评论状态
		/// </summary>
		/// <param name="articleID"></param>
		/// <returns></returns>
		protected string GetCommentState(int articleID)
		{
			InfoCommentState commentState = null;
			string strCommentState;
			if (IsExistComment(articleID, ref commentState))
			{
				strCommentState = (commentState.IsClose == false) ? "是" : "<span class=\"Emphasize\">否</span>";
			}
			else
			{
				strCommentState = "<span class=\"Emphasize\">否</span>";
			}
			return strCommentState;
		}

		/// <summary>
		/// 设置评论状态
		/// </summary>
		/// <param name="articleID"></param>
		protected void SetCommentState(int articleID)
		{
			InfoCommentState commentState = new InfoCommentState();
			commentState.InfoType = Articles.INFO_TYPE;
			commentState.InfoId = articleID.ToString();

			if (IsExistComment(articleID, ref commentState))
			{
				commentState.IsClose = !commentState.IsClose;
			}
			else
			{
				commentState.IsClose = false;
			}

			if (commentState != null)
			{
				InfoCommentStates.SetInfoCommentState(commentState.InfoType, commentState.InfoId, commentState.IsClose);
			}
		}

		/// <summary>
		/// 文章信息是否存在评论
		/// </summary>
		/// <param name="articleID"></param>
		/// <param name="commentState"></param>
		/// <returns></returns>
		protected bool IsExistComment(int articleID, ref InfoCommentState commentState)
		{
			string infoType = Articles.INFO_TYPE;
			InfoCommentState infoCommentStateInfo = InfoCommentStates.GetItem(infoType, articleID.ToString());
			if (infoCommentStateInfo != null)
			{
				commentState = infoCommentStateInfo;
				return true;
			}
			return false;
		}
		#endregion


		protected void Page_Load(object sender, EventArgs e)
		{
			if (Articles.GetManageListRight())
			{
				if (!IsPostBack)
				{
					LoadList();
					Page.DataBind();
				}
			}
			else
			{
				Messages.Add(new PageMessage(false, null, PageMessageType.Error, Res.PermissionExceptionMessageTitle, Res.PermissionExceptionMessage));
			}
		}
	}
}
